package org.makcro.sms.services.chat.base.listeners;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import org.apache.log4j.Logger;
import org.makcro.sms.services.chat.base.dao.BulkMessageDao;
import org.makcro.sms.services.chat.base.service.EventManager;
import org.makcro.sms.services.chat.base.service.EventManager.EventParams;
import org.makcro.sms.services.chat.model.BulkMessage;

import com.klikmee.sms.cef.bulk.BulkSender.BulkParams;
import com.klikmee.sms.core.commons.events.AppEvent;
import com.klikmee.sms.core.commons.events.EventListener;

/**
 * Event listener for bulk messages events. Responsibilities: 1. Stores bulk
 * message to database it has been sent
 * 
 * @author makcro
 * 
 */
public class BulkMessageEventListener implements EventListener {

	// logger instance
	private Logger			logger	= Logger.getLogger( BulkMessageEventListener.class );

	// dao used to access bulk messages
	private BulkMessageDao	bulkMessageDao;

	@Override
	public void handleEvent(AppEvent appEvent) {
		// check for the type of event
		String eventType = appEvent.getEventType();
		if (eventType.equals( EventManager.BULK_MESSAGE_SENT )) {
			onBulkMessageSent( appEvent );
		}

	}

	/**
	 * Stores bulk message to database with meta data from the event
	 * 
	 * @param appEvent
	 *            bulk message sent event
	 */
	private void onBulkMessageSent(AppEvent appEvent) {
		// extract event data and construct bulk message
		Hashtable<BulkParams, Object> bulkMessageParams = appEvent.<Hashtable<BulkParams, Object>>getData(EventParams.BULK_PARAMS);
		
		Long coreId = appEvent.<Long>getData( EventParams.BULK_CORE_ID );
		
		String sender = (String) bulkMessageParams.get( BulkParams.SENDER );
		String text = (String) bulkMessageParams.get( BulkParams.TEXT );
		List<String> receivers = (List<String>) bulkMessageParams.get( BulkParams.RECEIVERS );
		
		// store bulk message
		BulkMessage message = new BulkMessage();
		message.setCoreId( coreId );
		message.setSendingDate( new Date() );
		message.setMessageText( text );
		message.setReceiver( receivers.get( 0 ) );
		message.setSender( sender );
		
		this.bulkMessageDao.create( message );
		logger.info( MessageFormat.format( "Stored bulk message with id [{0}] to database", message.getId() ) );
	}

	public void setBulkMessageDao(BulkMessageDao bulkMessageDao) {
		this.bulkMessageDao = bulkMessageDao;
	}

}
